import * as React from 'react';
import { CheckIcon, Hash } from 'lucide-react';

import { cn } from '@/lib/utils';
import {
  Command,
  CommandEmpty,
  CommandGroup,
  CommandInput,
  CommandItem,
  CommandList
} from '@/components/ui/command';
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
import { api } from '@/axios/instance';

type Props = {
  list?: TaskTag[];
  children: React.ReactNode;
  setTags([]): void;
  onSaveTags?(tags: TaskTag[]): void
  setTagList(tags: React.SetStateAction<TaskTag[]>): void;
};

export const PopoverMultiselect = ({ list: tagList = [], children, setTags, onSaveTags, setTagList }: Props) => {
  const [open, setOpen] = React.useState(false);
  const [valueTag, setValueTag] = React.useState('');
  const [list, setList] = React.useState<TaskTag[]>([]);

  const addOrRemove = (array: TaskTag[], element: string) => {
    const index = array.findIndex((item) => item.tag === element);
    let newArray: TaskTag[] = [...array];
    if (index === -1) {
      newArray.push({ tag: element, color: '' });
    } else {
      newArray.splice(index, 1);
    }
    setTags(newArray);
    return newArray;
  };

  const getTags = () => {
    const lcls = localStorage.getItem('selectedProjectId') || '';
    api.post('/api/TaskBoard/getTags', { project_id: lcls }).then((res) => setList(res.data.data));
  }

  React.useEffect(() => {
    if (open) {
      getTags();
    }
  }, [open])

  const onChangeOpen = (arg: boolean) => {
    setOpen(arg);
    if (arg === false && onSaveTags && !!tagList.length) {
      onSaveTags(tagList);
    }
  }

  return (
    <Popover open={open} onOpenChange={onChangeOpen}>
      <PopoverTrigger asChild>{children}</PopoverTrigger>
      <PopoverContent className='w-[200px] p-0 z-[99]'>
        <Command>
          <CommandInput placeholder='Найти тег...' className='h-9' onValueChange={setValueTag} value={valueTag.trimEnd()} />
          <CommandList>
            <CommandEmpty>Тег не найден</CommandEmpty>
            <CommandGroup>
              {
                valueTag.length > 0 && !list.some((item) => item.tag === valueTag) ? <CommandItem value={valueTag} onSelect={() => {
                  setTagList((prev) => addOrRemove(prev, valueTag));
                  setList((prev) => [...prev]);
                  setValueTag('');

                }}>
                  <Hash size={18} className='mr-2 text-slate-400' /> {valueTag}
                </CommandItem> : null
              }
              {list?.map((item, idx) => (
                <CommandItem
                  key={item.tag + idx}
                  value={item.tag}
                  onSelect={() => {
                    setTagList((prev) => addOrRemove(prev, item.tag));
                    // setOpen(false);
                  }}
                >
                  <Hash size={18} className='mr-2' /> {item.tag}
                  <CheckIcon
                    className={cn(
                      'ml-auto h-4 w-4',
                      tagList.some((j) => j.tag === item.tag) ? 'opacity-100' : 'opacity-0'
                    )}
                  />
                </CommandItem>
              ))}
            </CommandGroup>
          </CommandList>
        </Command>
      </PopoverContent>
    </Popover >
  );
};
